package com.shujia.scala

import scala.io.{BufferedSource, Source}

object Demo35Student {
  def main(args: Array[String]): Unit = {


    /**
      * 1、统计总分年级排名前十学生各科的分数
      *
      * 1、统计每个学生的总分
      *
      * 2、按总分排名
      *
      * 3、取前十的学生
      *
      * 4、关联获取学生各科的分数
      *
      */


    //1、读取分数表
    val source: BufferedSource = Source.fromFile("data/score.txt")
    val scores: List[String] = source.getLines().toList


    //2、取出学号和分数
    val idAndScore: List[(String, Double)] = scores.map(s => {
      val split: Array[String] = s.split(",")
      (split(0), split(2).toDouble)
    })


    //3、按学生分组
    val scoreGroup: Map[String, List[(String, Double)]] = idAndScore.groupBy(kv => kv._1)


    //4、计算学生的总分
    val idSumScore: Map[String, Double] = scoreGroup.map {
      case (id: String, scoAndIds: List[(String, Double)]) =>

        //计算学生的总分
        val scos: List[Double] = scoAndIds.map(kv => kv._2)

        val sumScore: Double = scos.sum

        //返回数据
        (id, sumScore)
    }

    //将map转换成list
    val sumScoreList: List[(String, Double)] = idSumScore.toList

    //5、按照总分降序排序
    val sortSumScore: List[(String, Double)] = sumScoreList.sortBy(kv => -kv._2)

    //6、取前十
    val top10: List[(String, Double)] = sortSumScore.take(10)

    //7、取出前十学生的学号
    val top10Ids: List[String] = top10.map(kv => kv._1)

    //8、取出前十学生各科的分数
    val top10Student: List[String] = scores.filter(sco => {
      val id: String = sco.split(",")(0)
      top10Ids.contains(id)
    })

    top10Student.foreach(println)
  }

}
